using System;
using System.Collections.Generic;
using System.Text;
using OhioState.Graphics.TextureProxy;
using System.Drawing;
using Tao.OpenGl;
using System.Drawing.Imaging;

namespace OSU_GL_Library
{
    public class TextureWriterHandler
    {
        private TextureWriterProxy textureWriterProxy;
        private OpenGLPanel glPanel;

        public TextureWriterHandler(OpenGLPanel glPanel, TextureWriterProxy textureWriterProxy)
        {
            this.glPanel = glPanel;
            this.textureWriterProxy = textureWriterProxy;
        }

        public Bitmap GetBitmap()
        {
            int width = GetTextureWidth();
            int height = GetTextureHeight();
            byte[] byte_buffer = GetByteArray();
            Bitmap bm = BitmapHelper.GetBitmapFromByteArray(byte_buffer, width, height);
            return bm;
        }

        public byte[] GetByteArray()
        {
            Texture2DHandler texture2DHandler = ((AssetManagerGL)glPanel.ResourceManager).GetItem(textureWriterProxy.GetTextureProxy()) as Texture2DHandler;
            if (texture2DHandler == null) return null;

            int width = texture2DHandler.Width;
            int height = texture2DHandler.Height;
            byte[] byte_buffer = new byte[width * height * 4];

            texture2DHandler.bind();
            Gl.glGetTexImage(Gl.GL_TEXTURE_2D, 0, Gl.GL_RGBA, Gl.GL_UNSIGNED_BYTE, byte_buffer);
            texture2DHandler.unbind();

            return byte_buffer;
        }

        public int GetTextureWidth()
        {
            Texture2DHandler texture2DHandler = ((AssetManagerGL)glPanel.ResourceManager).GetItem(textureWriterProxy.GetTextureProxy()) as Texture2DHandler;
            if (texture2DHandler == null) return 0;
            return texture2DHandler.Width;
        }

        public int GetTextureHeight()
        {
            Texture2DHandler texture2DHandler = ((AssetManagerGL)glPanel.ResourceManager).GetItem(textureWriterProxy.GetTextureProxy()) as Texture2DHandler;
            if (texture2DHandler == null) return 0;
            return texture2DHandler.Height;
        }
    }
}
